import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:fluttertoast/fluttertoast.dart';

class News extends StatefulWidget {
  News({Key? key}) : super(key: key);

  _NewsState createState() => _NewsState();
}

class _NewsState extends State<News> {
  List _list = [];
  final _scrollController = ScrollController();
  var page = 1;
  var pageSize = 20;
  var isMore = true;

  @override
  void initState() {
    super.initState();
    this._getData();
    _scrollController.addListener(() {
      //上拉加载更多
      if (_scrollController.position.pixels > _scrollController.position.maxScrollExtent - 50) {
        print("上拉加载更多");
        page++;
        this._getData();
      }
    });
  }

  _getData() async {
    if (isMore == false) return; //第二次请求数据不足不在请求
    var apiUrl = "https://api.guancha.cn/Appdata/newslist.json?id=homepage&newstype=1&page=$page";
    var result = await http.get(Uri.parse(apiUrl));
    if (result.statusCode == 200) {
      print(json.decode(result.body));
      Future.delayed(Duration(milliseconds: page == 1 ? 100 : 3000), () {
        var decode = json.decode(result.body);
        setState(() {
          if (page == 1) {
            this._list = decode["datas"];
            isMore = _list.length == pageSize;
          } else {
            this._list.addAll(decode["datas"]);
            page++;
            isMore = _list.length % pageSize == 0;
          }
        });
      });
    } else {
      print("失败${result.statusCode}");
    }
  }

  Future<void> _onRefreshs() async {
    print("下拉刷新");
    page = 1;
    await Future.delayed(Duration(milliseconds: 100), () {
      print("下拉刷新完成");
      _getData();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("新闻"),
        ),
        body: this._list.length > 0
            ? RefreshIndicator(
                onRefresh: _onRefreshs,
                child: ListView.builder(
                    itemCount: this._list.length,
                    controller: _scrollController,
                    itemBuilder: (context, index) {
                      var title = this._list[index]["title"];
                      var pic = this._list[index]["pic"];
                      var httpUrl = "https://m.guancha.cn/${this._list[index]["http_url"]}";
                      return Container(
                        margin: EdgeInsets.only(left: 10, right: 10, top: index == 0 ? 10 : 0),
                        decoration: const BoxDecoration(
                          color: Colors.white,
                        ),
                        child: InkWell(
                          child: Center(
                            child: Column(
                              children: [
                                ClipRRect(
                                  borderRadius: BorderRadius.circular(10.0), // 设置圆角半径为 10
                                  child: Image.network(
                                    pic,
                                    fit: BoxFit.cover,
                                    width: double.infinity, // 确保宽度填满父容器
                                    errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
                                      print("图片加载失败：$exception");
                                      // 返回一个占位图或错误提示
                                      return Image.asset(
                                        'images/error_image.webp', // 替换为您的失败图路径
                                        fit: BoxFit.cover,
                                        width: double.infinity, // 确保宽度填满父容器
                                      );
                                    },
                                  ),
                                ),
                                SizedBox(
                                  height: 40,
                                  child: Center(
                                      child: Text(
                                    title, style: const TextStyle(fontSize: 14, color: Colors.red, height: 1),
                                    maxLines: 2, // 最多显示两行
                                    overflow: TextOverflow.ellipsis, // 超出部分用省略号表示
                                  )),
                                ),
                                if (index == _list.length - 1) _getMoreWidget() else const SizedBox(height: 0, width: 0)
                                // ?(isMore ? const Text("正在加载中......") : const Text("加载完毕")):const SizedBox
                                // (height: 0,
                                // width:0)
                              ],
                            ),
                          ),
                          onTap: () {
                            Navigator.pushNamed(context, "/NewsContent", arguments: {"title": title, "url": httpUrl});
                          },
                        ),
                      );
                    }))
            : Text("正在加载中......"));
  }

  //加载中的圈圈
  Widget _getMoreWidget() {
    if (isMore) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              const Text(
                '加载中...',
                style: TextStyle(fontSize: 16.0),
              ),
              Container(
                margin: const EdgeInsets.only(left: 10.0),
                child: const SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(
                    strokeWidth: 1.0,
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    } else {
      return Container(
        alignment: Alignment.center,
        height: 40,
        child: Text("--我是有底线的--"),
      );
    }
  }
}
